import 'dart:convert' as convert;
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:http/http.dart' as http;
import 'package:kasax/commons/commons.dart';
import 'package:kasax_demos2/entry/entrys.dart';

/// 基于http: ^0.13.3
/// https://pub.dev/packages/http/versions/0.13.3/example
/// https://reqbin.com/ 在线请求测试
class HttpDemo extends StatefulWidget {
  const HttpDemo({Key? key}) : super(key: key);

  @override
  _HttpDemoState createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {
  List<Posts> posts = <Posts>[];

  @override
  void initState() {
    super.initState();
    // testJson();
    fetchPost().then((value) {
      log("list.len: ${value.length}");
      setState(() {
        posts.addAll(value);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(child: buildContent());
  }

  Future<List<Posts>> fetchPost() async {
    log("fetchPost run");
    var response = await http.get(Uri.parse("https://resources.ninghao.net/demo/posts.json"));
    log("message: $response");
    List<Posts> postList = <Posts>[];
    if (response.statusCode == 200) {
      // log("msg body:${response.body}");
      var jsonResponse = convert.jsonDecode(response.body) as Map<String, dynamic>;
      // log("jsonResponse: $jsonResponse");

      // 原始使用方式
      // List posts = jsonResponse["posts"];
      // // log("posts: $posts");
      // posts.forEach((element) {
      //   postList.add(Posts.fromJson(element));
      // });
      // log("postList.len: ${postList.length} , posts.len: ${posts.length}");

      // 新的方式
      postList = jsonResponse["posts"].map<Posts>((item) => Posts.fromJson(item)).toList();
    }
    return postList;
  }

  void testJson() {
    log("---------- testJson start ----------");
    // json数据其实就是map
    final post = {'title': 'hello', 'description': 'nice to meet you.'};
    log("${post['title']}");

    // json => 字符串
    var postJsonStr = convert.jsonEncode(post);
    log("$postJsonStr");

    // 字符串转换json
    final postJsonConverted = convert.jsonDecode(postJsonStr);
    log("${postJsonConverted['title']}");

    // final postsModel = Posts.fromJson(postJsonConverted);
    // log("${postsModel.title} , ${postsModel.description}");

    log("---------- testJson end ----------");
  }

  buildContent() {
    return posts.isEmpty ? buildLoadingWidget() : buildListView2();
  }

  ListView buildListView2() {
    return ListView(
      children: posts
          .map<Widget>((e) => ListTile(
                title: Text(e.title),
                subtitle: Text(
                  e.description,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 3,
                ),
                leading: CircleAvatar(
                  backgroundImage: NetworkImage(e.imageUrl),
                ),
              ))
          .toList(),
    );
  }

  ListView buildListView() {
    return ListView.separated(
      itemCount: posts.length,
      itemBuilder: (context, index) {
        final post = posts[index];
        return ListTile(
          title: Text(post.title),
          subtitle: Text(post.description),
          leading: CircleAvatar(
            backgroundImage: NetworkImage(post.imageUrl),
          ),
        );
      },
      separatorBuilder: (context, index) => Divider(),
    );
  }
}
